package com.ship.dispatch.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ship.common.business.service.impl.BaseServiceImpl;
import com.ship.common.core.utils.BeanCopyUtils;
import com.ship.common.core.utils.BeanUtils;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.bean.TzFuelReport;
import com.ship.dispatch.bean.orderPay.SpPaymentOrder;
import com.ship.dispatch.bean.orderPay.SpPaymentOrderDetail;
import com.ship.dispatch.bo.TzFuelReportSumBo;
import com.ship.dispatch.bo.orderPay.SpPaymentOrderBO;
import com.ship.dispatch.bo.orderPay.SpPaymentOrderDetailBO;
import com.ship.dispatch.bpm.service.ProcessInstanceService;
import com.ship.dispatch.service.TzFuelDeliveryService;
import com.ship.dispatch.service.TzFuelReportService;
import com.ship.dispatch.mapper.TzFuelReportMapper;
import com.ship.dispatch.service.orderPay.SpPaymentOrderDetailService;
import com.ship.dispatch.service.orderPay.SpPaymentOrderService;
import com.ship.dispatch.util.NumberFormatUtil;
import com.ship.dispatch.util.StringUtils;
import com.ship.system.api.BpmInstanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author zhangyh
* @description 针对表【tz_fuel_report(燃油台账加油记录信息)】的数据库操作Service实现
* @createDate 2024-06-17 11:31:53
*/
@Service
public class TzFuelReportServiceImpl extends BaseServiceImpl<TzFuelReportMapper, TzFuelReport>
    implements TzFuelReportService{

    @Autowired
    @Lazy
    private ProcessInstanceService processInstanceService;

    @Autowired
    @Lazy
    private SpPaymentOrderService spPaymentOrderService;

    @Autowired
    @Lazy
    private SpPaymentOrderDetailService spPaymentOrderDetailService;

    @Autowired
    @Lazy
    private TzFuelDeliveryService tzFuelDeliveryService;

    @Override
    @Transactional
    public JsonResult add(TzFuelReport dto) {
        dto.setUpdatedBy(SecurityUtils.getUsername());
        dto.setUpdatedTime(new Date());
        dto.setFuelType("燃油加注");
        dto.setDataType(1);

        //同步数据至支付订单
        SpPaymentOrderBO orderBO = new SpPaymentOrderBO();
        orderBO.setOrderType(19);
        if(dto.getContractId() != null){
            orderBO.setContractType(5);
            orderBO.setContractId(dto.getContractId());
            orderBO.setContractName(dto.getContractName());
        }
        BigDecimal payMoney = BigDecimal.ZERO;
        if(dto.getVlsfoPrice() != null && dto.getVlsfoValue() != null){
            payMoney = payMoney.add(dto.getVlsfoPrice().multiply(dto.getVlsfoValue()));
        }
        if(dto.getLsmgoPrice() != null && dto.getLsmgoValue() != null){
            payMoney = payMoney.add(dto.getLsmgoPrice().multiply(dto.getLsmgoValue()));
        }
        orderBO.setShipName(dto.getShipName());
        orderBO.setPayAmount(payMoney);
        orderBO.setPayAmountUnit(1);
        orderBO.setApplicantPeople(SecurityUtils.getUsername());
        SpPaymentOrder orderResult = spPaymentOrderService.synchronousPayOrder(orderBO);

        SpPaymentOrderDetailBO orderDetail = new SpPaymentOrderDetailBO();
        if(orderResult != null){
            dto.setOrderId(orderResult.getId());
            orderDetail.setOrderId(orderResult.getId());
        }

        orderDetail.setShipName(dto.getShipName());
        orderDetail.setRefuelTime(dto.getFuelTime());
        orderDetail.setVlsfoOilQuantity(dto.getVlsfoValue().toString());
        orderDetail.setLsmgoOilQuantity(dto.getLsmgoValue().toString());
        orderDetail.setVlsfoOilPrice(dto.getVlsfoPrice());
        orderDetail.setLsmgoOilPrice(dto.getLsmgoPrice());
        orderDetail.setFuelSupplier(dto.getFuelSupplier());
        SpPaymentOrderDetail orderDetailResult = spPaymentOrderService.synchronousPayOrderDetail(orderDetail);
        if(orderDetailResult != null){
            dto.setOrderDetailId(orderDetailResult.getId());
        }
        this.baseMapper.insert(dto);

        //燃油记录有更新以后需要同步船只交还船历史信息
        tzFuelDeliveryService.fuelUpdateDeliveryInfo(dto.getFuelTime(),dto.getShipName());

        return JsonResult.success();
    }

    @Override
    public JsonResult<List<TzFuelReportSumBo>> getSummaryList(TzFuelReport dto) {
        List<TzFuelReportSumBo> resultList = new LinkedList<>();
        List<TzFuelReport> disList = this.baseMapper.selectList(
                new LambdaQueryWrapper<TzFuelReport>()
                        .select(TzFuelReport::getShipName)
                        .like(StringUtils.isNotBlank(dto.getShipName()),TzFuelReport::getShipName,dto.getShipName())
                        .like(StringUtils.isNotBlank(dto.getImo()),TzFuelReport::getImo,dto.getImo())
                        .groupBy(TzFuelReport::getShipName)
        );
        if(disList.size() == 0){
            return JsonResult.success(resultList);
        }
        List<String> shipNames = disList.stream().map(TzFuelReport::getShipName).collect(Collectors.toList());

        for (String shipName : shipNames) {
            TzFuelReportSumBo report = new TzFuelReportSumBo();
            report.setShipName(shipName);

            //最新的VLSFO
            TzFuelReport vlReport = this.baseMapper.selectOne(
                    new LambdaQueryWrapper<TzFuelReport>()
                            .eq(TzFuelReport::getShipName,shipName)
                            .isNotNull(TzFuelReport::getVlsfoValue)
                            .orderByDesc(TzFuelReport::getFuelTime,TzFuelReport::getId)
                            .last("limit 1")
            );
            if (vlReport != null){
                report.setVlsfoFuelType(vlReport.getFuelType());
                report.setVlsfoFuelTime(vlReport.getFuelTime());
                if(vlReport.getVlsfoValue() != null){
                    report.setVlsfoValueStr(NumberFormatUtil.numericFormatting(vlReport.getVlsfoValue()));
                }
                if(vlReport.getVlsfoPrice() != null){
                    report.setVlsfoPriceStr(NumberFormatUtil.numericFormatting(vlReport.getVlsfoPrice()));
                }
            }

            //最新的LSMGO
            TzFuelReport lsReport = this.baseMapper.selectOne(
                    new LambdaQueryWrapper<TzFuelReport>()
                            .eq(TzFuelReport::getShipName,shipName)
                            .isNotNull(TzFuelReport::getLsmgoValue)
                            .orderByDesc(TzFuelReport::getFuelTime,TzFuelReport::getId)
                            .last("limit 1")
            );
            if (lsReport != null){
                report.setLsmgoFuelType(lsReport.getFuelType());
                report.setLsmgoFuelTime(lsReport.getFuelTime());
                if(vlReport.getLsmgoValue() != null){
                    report.setLsmgoValueStr(NumberFormatUtil.numericFormatting(lsReport.getLsmgoValue()));
                }
                if(vlReport.getLsmgoPrice() != null){
                    report.setLsmgoPriceStr(NumberFormatUtil.numericFormatting(lsReport.getLsmgoPrice()));
                }
            }
            if(vlReport != null && lsReport != null){
                if(vlReport.getFuelTime().before(lsReport.getFuelTime())){
                    report.setFuelSupplier(lsReport.getFuelSupplier());
                    report.setUpdatedBy(lsReport.getUpdatedBy());
                    report.setUpdatedTime(lsReport.getUpdatedTime());
                }else{
                    report.setFuelSupplier(vlReport.getFuelSupplier());
                    report.setUpdatedBy(vlReport.getUpdatedBy());
                    report.setUpdatedTime(vlReport.getUpdatedTime());
                }
            }else{
                if(lsReport != null){
                    report.setFuelSupplier(lsReport.getFuelSupplier());
                    report.setUpdatedBy(lsReport.getUpdatedBy());
                    report.setUpdatedTime(lsReport.getUpdatedTime());
                }else if(vlReport != null){
                    report.setFuelSupplier(vlReport.getFuelSupplier());
                    report.setUpdatedBy(vlReport.getUpdatedBy());
                    report.setUpdatedTime(vlReport.getUpdatedTime());
                }
            }
            resultList.add(report);
        }
        return JsonResult.success(resultList);
    }

    @Override
    @Transactional
    public JsonResult dataUpdate(TzFuelReport dto) {
        if(dto.getId() == null){
            return JsonResult.failed("id不能为空");
        }
        TzFuelReport tzFuelReport = this.baseMapper.selectById(dto.getId());
        if(tzFuelReport == null){
            return JsonResult.failed("加油信息异常");
        }
        BeanCopyUtils.copy(dto,tzFuelReport);


        //同步数据至支付订单
        SpPaymentOrderBO orderBO = new SpPaymentOrderBO();
        orderBO.setId(tzFuelReport.getOrderId());
        orderBO.setOrderType(19);
        if(tzFuelReport.getContractId() != null){
            orderBO.setContractType(5);
            orderBO.setContractId(tzFuelReport.getContractId());
            orderBO.setContractName(tzFuelReport.getContractName());
        }
        BigDecimal payMoney = BigDecimal.ZERO;
        if(tzFuelReport.getVlsfoPrice() != null && tzFuelReport.getVlsfoValue() != null){
            payMoney = payMoney.add(tzFuelReport.getVlsfoPrice().multiply(tzFuelReport.getVlsfoValue()));
        }
        if(tzFuelReport.getLsmgoPrice() != null && tzFuelReport.getLsmgoValue() != null){
            payMoney = payMoney.add(tzFuelReport.getLsmgoPrice().multiply(tzFuelReport.getLsmgoValue()));
        }
        orderBO.setShipName(dto.getShipName());
        orderBO.setPayAmount(payMoney);
        orderBO.setPayAmountUnit(1);
        orderBO.setApplicantPeople(SecurityUtils.getUsername());
        SpPaymentOrder orderResult = spPaymentOrderService.synchronousPayOrder(orderBO);
        if(orderResult != null){
            tzFuelReport.setOrderId(orderResult.getId());
        }

        if(tzFuelReport.getOrderDetailId() != null){
            spPaymentOrderDetailService.getBaseMapper().deleteById(tzFuelReport.getOrderDetailId());
        }

        SpPaymentOrderDetailBO orderDetail = new SpPaymentOrderDetailBO();
        if(orderResult != null){
            orderDetail.setOrderId(orderResult.getId());
        }
        orderDetail.setShipName(tzFuelReport.getShipName());
        orderDetail.setRefuelTime(tzFuelReport.getFuelTime());
        orderDetail.setVlsfoOilQuantity(tzFuelReport.getVlsfoValue().toString());
        orderDetail.setLsmgoOilQuantity(tzFuelReport.getLsmgoValue().toString());
        orderDetail.setVlsfoOilPrice(tzFuelReport.getVlsfoPrice());
        orderDetail.setLsmgoOilPrice(tzFuelReport.getLsmgoPrice());
        orderDetail.setFuelSupplier(tzFuelReport.getFuelSupplier());
        SpPaymentOrderDetail orderDetailResult = spPaymentOrderService.synchronousPayOrderDetail(orderDetail);
        if(orderDetailResult != null){
            tzFuelReport.setOrderDetailId(orderDetailResult.getId());
        }
        this.baseMapper.updateById(tzFuelReport);

        //燃油记录有更新以后需要同步船只交还船历史信息
        tzFuelDeliveryService.fuelUpdateDeliveryInfo(dto.getFuelTime(),dto.getShipName());

        return JsonResult.success();
    }

    @Override
    @Transactional
    public JsonResult dataDelete(Long id) {
        TzFuelReport tzFuelReport = this.baseMapper.selectById(id);
        if(tzFuelReport == null){
            return JsonResult.failed("加油信息异常");
        }

        if(tzFuelReport.getApprovalStatus().intValue() == 0){
            return JsonResult.failed("请勿重复提交删除审批");
        }

        tzFuelReport.setApprovalStatus(0);
        this.baseMapper.updateById(tzFuelReport);

        //开启审批流程
        Map<String,Object> map = new HashMap<>();
        map.put("serviceType",1);
        map.put("module","tzFuelReport");
        map.put("moduleName","燃油台账");
        processInstanceService.createProcessInstance2(BpmInstanceService.SYSTEM_DELETE_BPM_KEY,map,id+"");
        return JsonResult.success("已提交删除审批");
    }

    @Override
    @Transactional
    public void dataDeleteRollback(String businessKey,int status) {
        TzFuelReport tzFuelReport = this.baseMapper.selectById(businessKey);
        if(tzFuelReport == null){
            return;
        }
        if(status == 1){
            //删除成功
            this.baseMapper.deleteById(businessKey);
            if(tzFuelReport.getOrderId() != null){
                spPaymentOrderService.getBaseMapper().deleteById(tzFuelReport.getOrderId());
            }
            if(tzFuelReport.getOrderDetailId() != null){
                spPaymentOrderDetailService.getBaseMapper().deleteById(tzFuelReport.getOrderDetailId());
            }

            //燃油记录有更新以后需要同步船只交还船历史信息
            tzFuelDeliveryService.fuelUpdateDeliveryInfo(tzFuelReport.getFuelTime(),tzFuelReport.getShipName());
        }else{
            //拒绝
            tzFuelReport.setApprovalStatus(2);
            this.baseMapper.updateById(tzFuelReport);
        }
    }
}




